#include "service/service.h"
#include "smart_serve_log.h"
#include "scheduler/simple.h"

namespace OHOS {
namespace SmartServe {

std::unique_ptr<Service> Service::instance_{nullptr};

Service::Service() : scheduler_(new SimpleScheduler())
{}

std::string Service::Serve(const std::string& request)
{
    SMART_SERVE_LOGI("[Serve] enter");
    auto response = apiHandler_.HandleRequest(request);
    SMART_SERVE_LOGI("[Serve] response: %s", response.c_str());
    return response;
}

void Service::Terminate()
{
    // TODO: Terminate binders, sensors

    // Scheduler
    scheduler_->Terminate();

    // Maintainer
    maintainer_.Terminate();

    // Models / Sessions
    //  1. 移除管理结构
    //  2. 发起终止
    //  3. 等待终止结束
    std::vector<std::unique_ptr<Model>> models;
    std::vector<std::unique_ptr<Session>> sessions;
    { // 1 & 2
        std::unique_lock<std::mutex> lock(msMgmtMutex_);

        for (auto& sItem : sessionManager_.allSessions_) {
            auto& session = sItem.second;
            session->AsyncTerminate();
            sessions.push_back(std::move(session));
        }

        for (auto& mItem : modelManager_.allModels_) {
            auto& model = mItem.second;
            model->AsyncTerminate();
            models.push_back(std::move(model));
        }
    }

    // 3. 等待终止结束
    for (auto& session : sessions) {
        session->WaitForTerminated();
    }
    sessions.clear();

    for (auto& model : models) {
        model->WaitForTerminated();
    }
    models.clear();
}

} // namespace SmartServe
} // namespace OHOS